from aip import AipSpeech  # 可以通过"pip install baidu-aip"命令安装
from services.SparkClient import SparkClient
from services.Privacy import Privacy


class AIService:
    def __init__(self):
        self.aip_speech_client = AipSpeech(Privacy.BAIDU_APP_ID.value, Privacy.BAIDU_API_KEY.value,
                                           Privacy.BAIDU_API_SECRET.value)  # 填入百度AI语音合成的appID，API Key和Secret Key
        self.aip_speech_client.setConnectionTimeoutInMillis(10000)
        self.aip_speech_client.setSocketTimeoutInMillis(10000)
        self.aip_synthesis_option = {"aue": 6, "per": 3, "spd": 6, "pit": 5, "vol": 7}

        self.spark_client = SparkClient(
            appid=Privacy.SPARK_APP_ID.value,
            api_key=Privacy.SPARK_API_KEY.value,
            api_secret=Privacy.BAIDU_API_SECRET.value,
        )

    def tts(self, text):
        """
            百度语音合成（TTS）
            :param text: 文本
            :return: PCM格式的音频数据
            """
        try:
            return self.aip_speech_client.synthesis(text, "zh", 1, self.aip_synthesis_option)
        except Exception:
            return self.aip_speech_client.synthesis(text, "zh", 1)

    def stt(self, speech, audio_format, rate):
        """
        百度语音识别（STT）
        :param speech: 语音数据
        :param audio_format: 音频格式，如'wav'、'pcm'
        :param rate: 采样率
        :return: 语音识别出来的文本
        """
        aip_asr_result = self.aip_speech_client.asr(speech, audio_format, rate)
        if aip_asr_result["err_no"] == 0:
            return " ".join(aip_asr_result["result"])
        else:
            print(str(aip_asr_result["err_no"]) + " " + aip_asr_result["err_msg"])
            return None

    def chat(self, question):
        return self.spark_client.chat(question)

